<?php

namespace App\Http\Controllers\Admin;

use App;
use App\Helper\Helper;
use App\Http\Controllers\Controller as BaseController;
use App\Http\Logic\Admin\NotesLogic;
use App\Common\Status;
use App\Http\Logic\PC\NoteLogic;
use App\Http\Requests\NoteRequest;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;
use PhpOffice\PhpSpreadsheet\Writer\Csv;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

class NotesController extends BaseController
{

    /**
     * @param Request $request
     * @return JsonResponse
     */
    public function notesList(Request $request): JsonResponse
    {
        $params   = $request->query();
        $pageSize = $request->query("pageSize", Status::PAGE_SIZE);
        $page     = $request->query("page", Status::PAGE);
        $data     = NotesLogic::getNoteList($params, $pageSize, $page);
        return $this->success(Status::SUCCESS, 'success', $data);
    }

    public function createResume(NoteRequest $request)
    {
        $params = $request->validated();

        # 附件id
        if (!isset($params["annex_id"]) || empty($params["annex_id"])) {
            return $this->error(Status::ERROR, '附件不可空');
        }
        if (!isset($params["att_name"]) || empty($params["att_name"])) {
            return $this->error(Status::ERROR, '附件不可空');
        }

        $res = NoteLogic::createResume($params, 2);

        if ($res["status"] == Status::SUCCESS) {
            $r = $params['id'] ? [] : ['id' => $res["id"]];
            return $this->success(Status::SUCCESS, 'success', $r);

        } else {
            return $this->error(Status::ERROR, $res["msg"]);
        }
    }

    public function delResume($id)
    {
        NoteLogic::delResume($id);

        return $this->success(Status::SUCCESS, 'success', []);
    }


    public function exportData2()
    {
        $key_head = [
            "姓名",
            "手机号",
            "出生日期",
            "学历",
            "工作年限",
            "期望岗位",
            "期望城市",
            "简历标题",
            "简历创建时间",
        ];

        $data = NotesLogic::getNoteList([], 0, 0, "exp");

        $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();

        $sheet = $spreadsheet->getActiveSheet();
        $sheet->setTitle('sheet1');

        foreach ($key_head as $key => $value) {
            $sheet->setCellValueByColumnAndRow($key + 1, 1, $value);
        }

        $row = 2;
        foreach ($data as $item) {
            $sheet->setCellValue('A' . $row, $item->user_name);
            $sheet->setCellValue('B' . $row, $item->mobile);
            $sheet->setCellValue('C' . $row, date("Y-m-d H:i:s", $item->birth));
            $sheet->setCellValue('D' . $row, $item->educational_info);
            $sheet->setCellValue('E' . $row, $item->work_year);
            $sheet->setCellValue('F' . $row, $item->position_category_name);
            $sheet->setCellValue('G' . $row, $item->work_city_name);
            $sheet->setCellValue('H' . $row, $item->att_name ?? "");
            $sheet->setCellValue('I' . $row, date("Y-m-d H:i:s", $item->created_at));
            $row++;
        }

        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
        $stream = $writer->save('php://output');
        // 返回数据流
        return response($stream)
            ->header('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
            ->header('Content-Disposition', 'attachment; filename="resume.xlsx"');





        // 方式 二：
//        $date     = date('Y-m-d');
//        $filePath = 'resume/doc/' . $date . '/';
//        $fileName = date('H-i-s') . ".csv";
//
//        if (!is_dir(storage_path($filePath))) {
//            File::makeDirectory(storage_path($filePath), 0777, true);
//        }
//
//        // 保存为 .xlsx 文件
//        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
//        $file   = storage_path($filePath) . $fileName ;
//        $writer->save($file);
//
//        // 将文件内容读取为二进制数据
//        $data = file_get_contents($file);
//
//        // 删除临时文件
//        unlink($file);
//
//        // 返回响应
//        return response($data)
//            ->header('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
//            ->header('Content-Disposition', 'attachment; filename="resume.xlsx"');



    }


    public function exportData(Request $request)
    {
        $params   = $request->query();

        if(!$params["tp"]  || empty($params["tp"])) {
            return "非法请求";
        }

        $key_head = [
            "姓名",
            "手机号",
            "出生日期",
            "学历",
            "工作年限",
            "期望岗位",
            "期望城市",
            "简历标题",
            "简历创建时间",
        ];

        $data = NotesLogic::getNoteList([], 0, 0, "exp");

        $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();

        $sheet = $spreadsheet->getActiveSheet();
        $sheet->setTitle('sheet1');

        foreach ($key_head as $key => $value) {
            $sheet->setCellValueByColumnAndRow($key + 1, 1, $value);
        }

        $row = 2;
        foreach ($data as $item) {
            $sheet->setCellValue('A' . $row, $item->user_name);
            $sheet->setCellValue('B' . $row, $item->mobile);
            $sheet->setCellValue('C' . $row, date("Y-m-d", $item->birth));
            $sheet->setCellValue('D' . $row, $item->educational_info);
            $sheet->setCellValue('E' . $row, $item->work_year);
            $sheet->setCellValue('F' . $row, $item->position_category_name);
            $sheet->setCellValue('G' . $row, $item->work_city_name);
            $sheet->setCellValue('H' . $row, $item->att_name ?? "");
            $sheet->setCellValue('I' . $row, date("Y-m-d H:i:s", $item->created_at));
            $row++;
        }
        date_default_timezone_set('Asia/Shanghai');
        if ($params["tp"] == "csv") {
            $writer = new Csv($spreadsheet);

            $date     = date('Y-m-d');
            $filePath = 'resume/doc/' . $date . '/';
            $fileName = $date . ".csv";
        } else if($params["tp"] == "xls"){
            $writer = new Xlsx($spreadsheet);

            $date     = date('Y-m-d');
            $filePath = 'resume/doc/' . $date . '/';
            $fileName = $date . ".xlsx";
        } else{
            return "非法请求";
        }


        if (!is_dir(storage_path($filePath))) {
            File::makeDirectory(storage_path($filePath), 0777, true);
        }

        $writer->save(storage_path($filePath) . $fileName);
//
//        // 将导出的文件移动到指定的文件夹
//        //        rename(storage_path($filePathTmp) . $fileName, storage_path($filePath) . $fileName);
//
//        // 返回下载链接或其他响应
        return response()->download(storage_path($filePath) . $fileName)->deleteFileAfterSend(true);

    }
}
